<template>
  <div>
    <px-form class="custom-form-ui visual-form" :model="queryParams" label-position="right" label-width="120px">
      <px-button type="primary" class="mr-[8px]" @click="getEqp">添加摄像头</px-button>
      <px-button type="primary" class="mr-[8px]" @click="seEqpByText">添加摄像头文本</px-button>
      <px-button type="danger" class="mr-[8px]" @click="delSelectEqp">删除所选摄像头</px-button>

      <px-button type="danger" class="mr-[8px]" @click="delAllEqp">清空摄像头</px-button>

      <px-form-item label="设备名称">
        <px-input v-model="queryParams.eqpId" placeholder="请输入设备编号" clearable @keyup.enter="queryTable" />
      </px-form-item>
      <px-button type="primary" @click="queryTable">查询</px-button>
      <px-button @click="resetTable">重置</px-button>
    </px-form>
    <CameraTable
      v-model:queryParams="queryParams"
      :data="tableData"
      :total="total"
      @queryTable="queryTable"
      @handleDelete="handleDelete"
      @selection-change="handleSelectionChange"
    />
    <camera-list v-model:visible="visible" :positionCode="null" @confirm="eqpListConfirm" />
    <px-dialog v-model="eqpTextOpen" title="请粘贴文本" width="30%" align-center @close="eqpTextClose">
      <px-input v-model="eqpText" :rows="30" type="textarea" maxlength="999999" show-word-limit status="warning" placeholder="Please input" />
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="eqpTextClose">取消</px-button>
          <px-button type="primary" @click="eqpTextConfirm"> 确认 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import CameraTable from "./cameraTable.vue";
import cameraList from "./cameraList.vue";

import {
  batchSave,
  delCameraListByids,
  delCameraListByPosition,
  delTreeAllEqp,
  delTreeItemByIds,
  updateMonitorPosition,
  queryCameraListById,
  queryCameraListByPosition
} from "@/api/visual/visualConfig";

const queryParams = ref({});

const visible = ref(false);
const tableData = ref([]);
const selectedTable = ref([]);
const eqpImgList = ref({});
const eqpTextOpen = ref(false);
const eqpText = ref("");
const total = ref(0);
const hseVisible = ref(false);
const isFilter = ref(false);
const props = defineProps({
  treeSelect: {
    type: Object || null
  },
  positionCode: {
    type: String || null
  },
  activeKey: {
    type: String || null
  },
  activeName: {
    type: String || null
  },
  eqpType: {
    type: String || null,
    default: "IFP"
  },
  imgUploadCut: {
    type: Number
  }
});

const emits = defineEmits(["handleUploadPic"]);
watch(
  () => [props.activeKey, props.treeSelect, props.imgUploadCut],
  val => {
    const [activeKey, treeSelect] = val;
    if (activeKey === props.activeName) {
      queryTable();
    }
  }
);
const getEqp = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  visible.value = true;
};
const eqpListConfirm = async selectIds => {
  if (selectIds.length > 0) {
    let res = null;
    const { code, type } = props.treeSelect;
    let saveData: any;
    if (type == "EQP") {
      saveData = selectIds.map(item => {
        return {
          eqpId: code,
          monitorEqpIsin: item
        };
      });
      res = await batchSave({ list: saveData });
    } else {
      saveData = {
        positionCode: code,
        isins: selectIds
      };
      res = await updateMonitorPosition(saveData);
    }

    if (res) {
      PxMessage.success("添加摄像头成功");
      visible.value = false;
      hseVisible.value = false;
      queryTable();
    } else {
      PxMessage.warning("添加摄像头失败");
    }
  }
};

watch(isFilter, () => {
  queryTable();
});
// 查询设备列表
const queryTable = async () => {
  if (!props.treeSelect) return;
  const { type } = props.treeSelect;
  let params: { positionCode?: string; queryParams?: Record<string, any>; eqpId?: string } = {
    positionCode: props.treeSelect.code,
    ...queryParams.value
  };
  let data = [];
  if (type == "EQP") {
    params = {
      eqpId: props.treeSelect.code,
      ...queryParams.value
    };
    data = (await queryCameraListById(params)) as any[];
  } else {
    data = (await queryCameraListByPosition(params)) as any[];
  }

  tableData.value = data || [];

  selectedTable.value = [];
};

const seEqpByText = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  eqpTextOpen.value = true;
};
const eqpTextClose = () => {
  eqpTextOpen.value = false;
  eqpText.value = "";
};
const delSelectEqp = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  if (!selectedTable.value || selectedTable.value.length === 0) {
    PxMessage.warning("请选择要删除的数据节点");
    return;
  }
  const names = pluck(selectedTable.value, "eqpName");
  PxMessageBox.confirm('是否确认删除名称为"' + names.toString() + "的设备？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const ids = pluck(selectedTable.value, "id");
      const res = await delTreeItemByIds({ ids });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      await queryTable();
    })
    .catch(() => {});
};
const delAllEqp = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  const { code: positionCode, name } = props.treeSelect;
  PxMessageBox.confirm('是否确认删除名称为"' + name + "下的所有设备的数据项？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const res = await delTreeAllEqp({ positionCode });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      await queryTable();
    })
    .catch(() => {});
};

const handleDelete = async row => {
  PxMessageBox.confirm('是否确认删除设备属性id为"' + row.id + '"的数据项？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const { type } = props.treeSelect;
      let params: { positionCode?: string; isins?: Array<any>; eqpId?: string } = {
        positionCode: props.treeSelect.code,
        isins: [row.eqpIsin]
      };
      let data;
      if (type == "EQP") {
        // params = {
        //   eqpId: props.treeSelect.code,
        //   ...queryParams.value
        // };
        data = await delCameraListByids({ ids: [row.id] });
      } else {
        data = await delCameraListByPosition(params);
      }

      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryTable();
    })
    .catch(() => {});
};

const handleSelectionChange = datas => {
  selectedTable.value = datas;
};
const resetTable = () => {
  queryParams.value = {};
  queryTable();
};
const eqpTextConfirm = async () => {
  if (!eqpText.value) {
    PxMessage.warning("请输入文本");
    return;
  }

  try {
    const saveData = eqpText.value.split("\n");
    await eqpListConfirm(saveData);
    // const res = await batchSave(saveData.filter(item => item.eqpId));
    // if (res) {
    //   PxMessage.success("添加设备成功");
    //   queryTable();
    //   eqpTextClose();
    // } else {
    //   PxMessage.warning("添加设备失败");
    // }
  } catch (error) {
    console.error(error);
    PxMessage.warning("添加设备失败");
  }
};
function pluck(array, key) {
  return array.map(item => item[key]);
}
</script>
